<template>
  <div>
    <!--自定义事件 add事件  @add  该方法只有在父子组件间有效-->
    <Search @add="add"/>
    <!-- 多级组件间的通信  pubsub-js 发布订阅-->
    <List :tasks="tasks"/>
    <ListInfo :clearFinished="clearFinished" :selectAll="selectAll" :tasks="tasks"/>
  </div>
</template>

<script>
  import PubSub from "pubsub-js"
  import LS from "../../../util/storage"
  import Search from "./Search"
  import List from "./List"
  import ListInfo from "./ListInfo"

  export default {
    name: "Selector",
    components: {
      Search,
      List,
      ListInfo
    },
    mounted() {
      // 组件间的通信 订阅消息
      PubSub.subscribe("del", (event, msg) => {
        this.del(msg)
      })
    },
    data() {
      return {
        // tasks: [{check: false, title: 'a'}, {check: true, title: 'b'}, {check: false, title: 'c'}]
        tasks: LS.lsGet("tasks", "[]")
      }
    },
    methods: {
      add(task) {
        this.tasks.unshift(task);
      },
      del(i) {
        this.tasks.splice(i, 1);
      },
      clearFinished() {
        this.tasks = this.tasks.filter(v => !v.check);
      },
      selectAll(selected) {
        this.tasks.forEach(v => v.check = selected);
      }
    },
    watch: {
      tasks: {
        // 深度监事
        deep: true,
        handler(newVal, oldVal) {
          LS.lsPut("tasks", newVal)
        }
      }
    }
  }
</script>

<style scoped>

</style>
